package saas.dev.cloud.util;

import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * StreamMap工具类
 *
 * @author : y1
 * @className : StreamMapUtils
 * @date: 2022/12/5 09:12
 * @description : StreamMap工具类
 */
public class StreamUtils {
    /**
     * 根据对象字段转换List
     *
     * @param list
     * @param mapper
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> List<R> toListByField(List<T> list, Function<? super T, ? extends R> mapper) {
        return list.stream().map(mapper).collect(Collectors.toList());

    }

    /**
     * 根据对象字段转换Map
     *
     * @param list
     * @param keyMapper
     * @param valueMapper
     * @param <T>
     * @param <K>
     * @param <U>
     * @return
     */
    public static <T, K, U> Map<K, U> toMapByField(List<T> list, Function<? super T, ? extends K> keyMapper,
                                                   Function<? super T, ? extends U> valueMapper) {
        return list.stream().collect(Collectors.toMap(keyMapper, valueMapper));
    }

    /**
     * 根据对象字段转换Map
     *
     * @param list
     * @param keyMapper
     * @param valueMapper
     * @param mergeFunction
     * @param <T>
     * @param <K>
     * @param <U>
     * @return
     */
    public static <T, K, U> Map<K, U> toMapByField(List<T> list, Function<? super T, ? extends K> keyMapper,
                                                   Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction) {
        return list.stream().collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction));
    }

}
